$(function() {

    /*
     * Facilities & Services
     */
    var log = console.log;
    var lang = new Array();
    lang['filter.filtering'] = 'Filtering';

    var API = {
        Data: {
            facility_id: new Array(),
            price_id: new Array(),
            stars_id: new Array(),
            distances_sea_id: new Array(),
            distances_center_id: new Array(),
            acc_type_id: new Array(),
            facility_item: new Array(),
            price_item: new Array(),
            stars_item: new Array(),
            distances_sea_item: new Array(),
            distances_center_item: new Array(),
            acc_type_item: new Array(),
            listElems: new Array()
        },
        Filter: {
            facility: function() {

                API.Data.facility_id = new Array();
                $.each(items, function(n, item) {   // idemo kroz objekte

                    var count_item = API.Data.facility_item.length; // broji duzinu ukljucenih filtera
                    var cnt = 0; // brojac pronadjenih filtera

                    if ((typeof this.all_attributes !== 'undefined') && (this.all_attributes !== null)) {

                        $.each(this.all_attributes, function(attribute_id, n) {   // idemo kroz pripremljene atribute

                            $.each(API.Data.facility_item, function(n, item_id) {    // idemo kroz ukljucene filter atribute

                                if (attribute_id === item_id)
                                    cnt++;
                            });
                        });
                        if (count_item === cnt) {
                            API.Data.facility_id.push(parseInt(item.object_ID));
                            //log('PUSH');
                        }

                    }
                });
            },
            price: function() {     // Bilo koja vrijednost iz price_item ako je nadjena, ukljucujemo taj objekat

                API.Data.price_id = new Array();
                cnt = 0;
                $.each(items, function(n, item) { // idemo kroz objekte

                    //            if (cnt == 4)
                    //                return;
                    //
                    //            cnt++;

                    var OBJECT_FOUND = false;
                    $.each(API.Data.price_item, function(n, rng) { // idemo kroz price range

                        if (!OBJECT_FOUND) {    // ovo koristimo umjesto izlaska break 2;

                            var prc_range = rng.split(",");
                            if (prc_range[1] === '-1')
                                prc_range[1] = 999999;

                            if (!preview) {

                                //                                log('not_preview')

                                $.each(item.rooms, function(n, room) { // idemo kroz sobe

                                    var price = parseFloat(room.selling_price);
                                    if ((price >= prc_range[0]) && (price < prc_range[1])) {

                                        API.Data.price_id.push(parseInt(item.object_ID));
                                        OBJECT_FOUND = true;
                                        return false; // ovdje izlazimo iz soba

                                    }

                                });

                            } else {

                                //                                log('is_preview')


                                var price = parseFloat(item.lowest_price);
                                if ((price >= prc_range[0]) && (price < prc_range[1])) {

                                    API.Data.price_id.push(parseInt(item.object_ID));
                                    OBJECT_FOUND = true;
                                    return false; // ovdje izlazimo iz soba

                                }

                            }
                        }

                    });
                });
            },
            stars: function() {

                API.Data.stars_id = new Array();
                $.each(items, function(n, item) { // idemo kroz objekte

                    if (item.object_number_of_stars == "")
                        item.object_number_of_stars = 0;
                    $.each(API.Data.stars_item, function(n, star) { // idemo kroz stars_item

                        if (star == item.object_number_of_stars) {
                            API.Data.stars_id.push(parseInt(item.object_ID));
                            return false; // ovdje izlazimo iz stars_item
                        }

                    });
                });
            },
            distances: function(attribute, distance) {

                if (attribute === 'object_distance_from_the_sea') {
                    API.Data.distances_sea_id = new Array();
                } else {
                    API.Data.distances_center_id = new Array();
                }

                $.each(items, function(n, item) { // idemo kroz objekte

                    if (item[attribute] === "")
                        item[attribute] = 999999;
                    if (parseInt(distance) >= parseInt(item[attribute])) {

                        if (attribute === 'object_distance_from_the_sea') {
                            API.Data.distances_sea_id.push(parseInt(item.object_ID));
                        } else {
                            API.Data.distances_center_id.push(parseInt(item.object_ID));
                        }
                    }
                });
            },
            acc_type: function() {

                API.Data.acc_type_id = new Array();
                $.each(items, function(n, item) { // idemo kroz objekte

                    $.each(API.Data.acc_type_item, function(n, acc_type) { // idemo kroz acc_type_item

//                        log(acc_type);
                        if (acc_type == item.object_type_type) {
                            API.Data.acc_type_id.push(parseInt(item.object_ID));
                            return false; // ovdje izlazimo iz acc_type_item
                        }

                    });

                });

            },
            init: function() {

                API.Data.listElems = $('#results li'); // Get all accommodation list

                $('.filterelement').live('click', function() {

                    if ($("#results").isMasked()) {
                        return false;
                    }

                    $("#results").mask(lang['filter.filtering'] + "...");
                    if ($(this).hasClass('inactive')) {
                        $(this).removeClass('inactive');
                        $(this).addClass('active');
                    } else {
                        $(this).removeClass('active');
                        $(this).addClass('inactive');
                    }
                    ;

                    var category = $(this).attr('data-category');
                    var active = $(this).hasClass('active');
                    var id = $(this).attr('data-id');

                    function action_delay() {

                        API.Filter.doFilter(category, active, id);
                        $("#results").unmask();
                    }

                    var randomnumber = 501 + Math.floor(Math.random() * 501);

                    window.setTimeout(function() {
                        action_delay();
                    }, randomnumber);
                    return false;
                });

                //                if ($(window).width() > 900) {
                //
                //                    var height = $('.mask-height').height();
                //                    $('.results-holder').height(height);
                //                    $('#results').height(height);
                //                }

                $('.collapse-filter').multiAccordion({
                    active: [0, 1, 2, 3],
                    click: function(event, ui) {
                        //console.log('clicked')
                    },
                    init: function(event, ui) {
                        //console.log('whoooooha')
                    },
                    tabShown: function(event, ui) {
                        //console.log('shown')
                    },
                    tabHidden: function(event, ui) {
                        //console.log('hidden')
                    }
                });

                $('.collapse-filter').multiAccordion("option", "active", [0, 1, 2, 3]);

            },
            doFilter: function(category, active, id) {

                switch (category) {

                    case 'filter_facilities':

                        if (active) {
                            API.Data.facility_item.push(id);
                        } else {

                            API.Data.facility_item.splice($.inArray(id, API.Data.facility_item), 1);
                        }

                        if (API.Data.facility_item.length > 0) {
                            API.Filter.facility();
                        } else {
                            API.Data.facility_id = new Array();
                        }

                        break;
                    case 'filter_price':

                        if (active) {
                            API.Data.price_item.push(id);
                        } else {
                            API.Data.price_item.splice($.inArray(id, API.Data.price_item), 1);
                        }

                        if (API.Data.price_item.length > 0) {
                            API.Filter.price();
                        } else {
                            API.Data.price_id = new Array();
                        }

                        break;
                    case 'filter_stars':

                        if (active) {
                            API.Data.stars_item.push(id);
                        } else {
                            API.Data.stars_item.splice($.inArray(id, API.Data.stars_item), 1);
                        }

                        if (API.Data.stars_item.length > 0) {
                            API.Filter.stars();
                        } else {
                            API.Data.stars_id = new Array();
                        }

                        break;
                    case 'beach_distance':

                        if (active) {
                            API.Data.distances_sea_item[0] = id;
                            API.Filter.distances('object_distance_from_the_sea', API.Data.distances_sea_item[0]);
                        } else {
                            API.Data.distances_sea_id = new Array();
                            API.Data.distances_sea_item = new Array();
                        }

                        break;
                    case 'center_distance':

                        if (active) {
                            API.Data.distances_center_item[0] = id;
                            API.Filter.distances('object_distance_from_the_center', API.Data.distances_center_item[0]);
                        } else {
                            API.Data.distances_center_id = new Array();
                            API.Data.distances_center_item = new Array();
                        }

                        break;

                    case 'filter_acc_type':

                        if (active) {
                            API.Data.acc_type_item.push(id);
                        } else {
                            API.Data.acc_type_item.splice($.inArray(id, API.Data.acc_type_item), 1);
                        }

                        if (API.Data.acc_type_item.length > 0) {
                            API.Filter.acc_type();
                        } else {
                            API.Data.acc_type_item = new Array();
                        }

                        break;
                }   // end switch

                API.DoAllArrays();
            }
        },
        Slider: {
            init: function() {

                $(".slider").slider({
                    animate: true,
                    range: "min",
                    value: 0,
                    min: 0,
                    max: 200,
                    step: 50,
                    change: API.Slider.Change

                });

            },
            Change: function(event, ui) {

                //                log('SliderChange');

                data_id = $(this).attr('data-id');
                $("#results").mask(lang['filter.filtering'] + "...");
                value = API.Slider.UIValue(ui.value);
                $("#" + data_id).html(value);
                function action_delay() {

                    API.Filter.doFilter(data_id, value, value);
                    $("#results").unmask();
                }

                var randomnumber = 501 + Math.floor(Math.random() * 501);

                window.setTimeout(function() {
                    action_delay();
                }, randomnumber);
                return false;
            },
            UIValue: function(value) {

                switch (value) {
                    case 0:
                        return 0;
                    case 50:
                        return 100;
                    case 100:
                        return 300;
                    case 150:
                        return 500;
                    case 200:
                        return 1000;
                }

            }

        },
        DoAllArrays: function() {

            var all_id = [API.Data.facility_id, API.Data.price_id, API.Data.stars_id, API.Data.distances_sea_id, API.Data.distances_center_id, API.Data.acc_type_id];
            var all_item = [API.Data.facility_item, API.Data.price_item, API.Data.stars_item, API.Data.distances_sea_item, API.Data.distances_center_item, API.Data.acc_type_item];
            var selected = new Array();
            var final = new Array();

            _.each(all_item, function(arr, index) {

                if (arr.length > 0)
                    selected.push(all_id[index]);

            });


            if (selected.length > 1) {
                //            log('intersection')
                final = _.intersection.apply(_, selected);
            } else if (selected.length === 1) {
                //            log('equals');
                final = selected[0];
            } else {
                final = new Array();
            }

            //        log(final)

            if (selected.length > 0) {

                $('#results li').remove();

                $.each(final, function(i, item) { // idemo kroz filter niz

                    $(API.Data.listElems).each(function(index) {
                        if ($(this).attr('id') === 'box-' + item) {
                            $('#results ul').append($(this))
                        }

                    });

                });

            } else {
                $('#results ul').html(API.Data.listElems);
            }

//            API.Pager.init();

            $('#cnt_results').html($('#results li').length);

        },
        Gallery: {
            Data: {
            },
            init: function() {

                $.each(items, function(n, item) {   // idemo kroz objekte
                    var index = 0;
                    $.each(item.photos, function(n, photo) {   // idemo kroz slike
                        var thumb = HOST_URL_HOTELS + 'gallery/' + photo.path + '/thumb_182x123/' + photo.photo_name;
                        var img = $('<img>'); //Equivalent: $(document.createElement('img'))
                        img.attr('src', thumb);
                        img.appendTo('#box-' + item.object_ID + ' .carousel .carousel-inner .item:eq(' + index + ') a');
                        index++;

                    });
                });

            }

        },
        Pager: {
            init: function() {
                $('#results').pajinate({
                    items_per_page: 8,
                    item_container_id: "#paging_cont",
                    wrap_around: true,
                    nav_label_first: '<<<',
                    nav_label_last: '>>>',
                    nav_label_prev: '<<',
                    nav_label_next: '>>',
                });
            }
        }
    };

    $(window).load(function() {
//        API.Gallery.init();
        API.Filter.init(); // Must go afther Gallery init to get photos loaded
//        API.Slider.init();
//        API.Pager.init();
    });

});